package com.ja.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ja.config.WebsiteStateConfig;
import com.ja.domain.Admin;
import com.ja.domain.AdminUser;
import com.ja.domain.KeFuAutomatic;
import com.ja.domain.KeFuChat;
import com.ja.domain.KeFuQuick;
import com.ja.domain.Lsltjl;
import com.ja.domain.RedPacket;
import com.ja.domain.TodayRecord;
import com.ja.domain.User;
import com.ja.sevice.BackManagerService;
import com.ja.sevice.IUserService;
import com.ja.sevice.KeFuService;
import com.ja.sevice.LiushuiService;
import com.ja.sevice.RedPacketService;
import com.ja.sevice.YunyingbbService;
import com.ja.util.DateUtil;
import com.ja.util.JsonResult;
import com.ja.util.RedPacketUtil;

import sun.misc.BASE64Encoder;

/**
 * 在线客服咨询--聊天室聊天
 * @author Administrator
 * @DATE 2018年9月18日
 *
 */
@SuppressWarnings("restriction")
@Controller
@RequestMapping("/chat")
public class ChatController {
	
	public static int falses;
	
	@Autowired
	private LiushuiService liushuiService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private KeFuService kefuService;
	
	@Autowired
	private RedPacketService redPacketService;
	
	@Autowired
	private YunyingbbService yunyingbbService;
	
	@Autowired
	private BackManagerService managerService;
	
	@RequestMapping("/mykefu")
	public ModelAndView mykefu(){
		return new ModelAndView("include/chat").addObject("flag", ChatController2.map.get("1")==null);
	}
	
	@RequestMapping("/userKefu")
	public ModelAndView userKefu(){
		return new ModelAndView("include/chat");
	}
	
	/**
	 * 获取当前在线的客服
	 * @param type 客服类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/kefu")
	public JsonResult kefu(Integer type,HttpSession session) {
		Map<String, Session> map = ChatController2.map;
		Random randoms = new Random();
		List<AdminUser> kefus = new ArrayList<AdminUser>();
		AdminUser admin = new AdminUser();
		for (Map.Entry<String, Session> kefu : map.entrySet()) {
				if(kefu.getKey().contains("kefu")) {
				AdminUser admins = kefuService.findByIdAmdinUser(Integer.parseInt(kefu.getKey().replace("kefu", "")));
					if (type == admins.getAdmin_type()) {
						kefus.add(admins);
					}else {
							kefus.add(admins);
					}
				}
			}
		if (kefus.size() > 0) {
			int random = randoms.nextInt(kefus.size());
			admin = kefus.get(random);
		}
		User user = (User)session.getAttribute("user");
		return new JsonResult(String.valueOf(user.getId()), admin);
	}
	
	/**
	   *   方法名：openredPack   
	   *   描述：     聊天室领取红包所需条件                  TODO   
	   *   参数：    @param id 用户id
	   *   参数：    @param session
	   *   参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/openredPack")
	public JsonResult openredPack(Integer id,HttpSession session){
		String message="";
		User u1 =(User) session.getAttribute("user");
		TodayRecord record = yunyingbbService.findOperateRecord("", "", u1.getName(),2);
		Double lishi = record.getChongzhi();//用户的充值总计
		TodayRecord record2 = yunyingbbService.findByTimeUserRechargeTotal(DateUtil.findFormatDate(),DateUtil.getLast12Months(0),u1.getId());
		Double benyue = record2.getZxtikuan()+record2.getRgkoukuan();//用户的本月充值总计
		Double jinri = record2.getZxchongzhi()+record2.getRgjiakuan();//用户的今日充值总计
		/** 系统红包所需 */
		
		double mrsx = Double.parseDouble(WebsiteStateConfig.configs.get("meiriJine"));
		double mysx = Double.parseDouble(WebsiteStateConfig.configs.get("meiyueJine"));
		double lssx = Double.parseDouble(WebsiteStateConfig.configs.get("lishiJine"));
		double yesx = Double.parseDouble(WebsiteStateConfig.configs.get("yueJine"));
		
		RedPacket redPacket = redPacketService.searchById(id);
		RedPacket redPacket2=new RedPacket(redPacket);
		redPacket2.setLingqu(jiami(redPacket2.getLingqu()));
		redPacket2.setRedpack(jiami(redPacket2.getRedpack()));
		
		String redpack[] = redPacket.getRedpack().split(",");
		String lingqu[] = redPacket.getLingqu().split(",");
		for (String string : lingqu) {
			if (string.equals(u1.getId().toString())) {
				return new JsonResult("您已经领取过这个红包", redPacket2);
			}
		}
		if (Integer.parseInt(redPacket.getCount())==lingqu.length-1) {
			return new JsonResult("红包已被抢完了", redPacket2);
		}
		u1 = userService.getUserByid(u1.getId());
		if(redPacket.getUserid()==0) {
			if (u1.getBalance() < yesx) {
				message = "系统红包余额条件不足,暂时无法领取系统红包!";
				return new JsonResult(message, "");
			}
			if (jinri < mrsx) {
				message = "今日充值金额不足,暂时无法领取系统红包!";
				return new JsonResult(message, "");
			}
			if (benyue < mysx) {
				message = "本月充值金额不足,暂时无法领取系统红包!";
				return new JsonResult(message, "");
			}
			if (lishi < lssx) {
				message = "历史充值金额不足,暂时无法领取系统红包!";
				return new JsonResult(message, "");
			}
		}
		redPacketService.updredPack(redPacket.getId(),redPacket.getLingqu()+u1.getId()+",");
		String x=redpack[lingqu.length-1];
		if (Integer.parseInt(x)<10) {
			x = "0" + x;
		}
		x = x.substring(0,x.length()-1)+"."+x.substring(x.length()-1);
		redPacket.setJine(x);
		redPacket2.setJine(x);
		String orderNum = "HB"+DateUtil.DateFormatOrderNum()+u1.getId();
		liushuiService.addActivityRecord(u1, orderNum,true, Double.parseDouble(x), "红包领取", 2);
		
		if (redPacket2.getType().equals("拼手气红包")) {
			redPacket2.setType("金额随机");
		}else {
			redPacket2.setType("金额固定");
		}
		User user = userService.getUserByid(redPacket.getUserid());
		redPacket2.setRedpack(user.getNicheng());
		redPacket2.setLingqu(user.getAvatar());
		return new JsonResult("", redPacket2);
	}
	
	private static String jiami(String str) {
		str=new BASE64Encoder().encode(str.getBytes());
		return str;
	}
	
	/**
	  *   方法名：chatAll   
	  *   描述：                       TODO   
	  *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/chatAll")
	@ResponseBody
	public JsonResult chatAll() {
		Admin admin = managerService.inquireAll();
		if (ChatController4.num == 0) {
			return new JsonResult(null, -1);
		}
		Long time = ChatController4.midTime14;
		if (time == null) {
			time = Long.parseLong(admin.getTime().trim());
			return new JsonResult(null, time);
		} else {
			return new JsonResult(null, time * 1000);
		}
	}
	/**
	   *   方法名：getUserByid   
	   *   描述：    根据id查询用的信息                    TODO   
	   *   参数：    @param id 用户id
	   *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/getUserById")
	@ResponseBody
	public JsonResult getUserByid(Integer id) {
		return new JsonResult("",userService.getUserByid(id));
	}
	
	/**
	   *   方法名：speechChat   
	   *   描述：     用户聊天室发言                  TODO   
	   *   参数：    @param session
	   *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/speechChat")
	@ResponseBody
	public JsonResult speechChat(HttpSession session) {
		User user = (User) session.getAttribute("user");
		if(user.getState()==2){
			return new JsonResult("1","试玩账号无法进行发言!");
		}
		TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(),2);
		Double historyMoney = record.getChongzhi();//用户的充值总计
		if (historyMoney < Double.parseDouble(WebsiteStateConfig.configs.get("money"))) {
			return new JsonResult("1","历史充值金额不足,无法进行发言!");
		}
		return new JsonResult("2", "历史充值金额满足,可以进行发言!");
	}
	
	/**
	 * 
	   *   方法名：timedRedEnvelopes   
	   *   描述：                       TODO   
	   *   参数：    @param num
	   *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/timedRedEnvelopes")
	@ResponseBody
	public JsonResult timedRedEnvelopes(int num){
		if(falses==num){
			return new JsonResult(null,falses);
		}
		falses = num;
		Admin admin = managerService.inquireAll();
		while(true){
			if(falses==0){
				return new JsonResult(null,falses);
			}
			try {
				Thread.sleep(Integer.parseInt(admin.getTime().trim()));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String x="";
			String type="固定红包";
			if (admin.getTypeofredenvelopes().contains("普通")) {
				List<Integer> list=RedPacketUtil.splitRedPackets((int) (Double.parseDouble(admin.getRedenvelopes())), admin.getNumberofredpackets());
				x=list.toString().replace("[", "").replace("]", "").replace(" ", "");
				type="拼手气红包";
			}else {
				for (int i = 0; i < admin.getNumberofredpackets(); i++) {
					x+=((Integer.parseInt(admin.getRedenvelopes())*10)+",");
				}
				x=x.substring(0, x.length()-1);
			}
			RedPacket redPacket=new RedPacket(0, new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()), type, admin.getRedenvelopes(), String.valueOf(admin.getNumberofredpackets()),admin.getLeavingamessage(), x, 0);
			redPacketService.insert(redPacket);
		}
	}
	
	/**
	 * 
	   *   方法名：LatestRedenvelopes   
	   *   描述：   添加聊天记录                    TODO   
	   *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/LatestRedenvelopes")
	@ResponseBody
	public JsonResult LatestRedenvelopes(){
		RedPacket r = redPacketService.LatestRedenvelopes();
		Lsltjl l = new Lsltjl();
		User user = liushuiService.chax(r.getUserid());
		l.setId(r.getId());
		l.setUserid(r.getUserid());
		l.setCreattime(r.getCreattime());
		l.setType(r.getType());
		l.setJine(r.getJine());
		l.setCount(r.getCount());
		l.setDesc(r.getDesc());
		l.setRedpack(r.getRedpack());
		l.setState(r.getState());
		l.setLingqu(r.getLingqu());
		l.setAvatar(user.getAvatar());
		l.setName(user.getNicheng());
		return new JsonResult(null,l);
	}
	
	/**
	 * 
	 * 
	 * --------------客服设置
	 * 
	 * 
	 */
	
	/**
	 * 根据关键词查询快捷回复语句
	 * @param keyWord 关键词
	 * @return
	 */
	
	@RequestMapping("/findLikeContentType")
	@ResponseBody
	public JsonResult findLikeContentType(String keyWord){
		keyWord.replaceAll("&nbsp;","").replaceAll(" ", "");
		List<KeFuQuick> quick = kefuService.findLikeContentType(1, keyWord);
		return new JsonResult("",quick);
	}
	
	/**
	 * 查询连接会话时的自动回复
	 * @return
	 */
	
	@RequestMapping("/findTypeKeFuAutomatic")
	@ResponseBody
	public JsonResult findTypeKeFuAutomatic(){
		List<KeFuAutomatic> automatic = kefuService.findTypeKeFuAutomatic(1);
		return new JsonResult("",automatic);
	}
	
	/**
	 * 查询客服咨询聊天记录
	 * @param kefu_id 客服id
	 * @param user_id 用户id
	 * @return
	 */
	@RequestMapping("/getChatRecord")
	@ResponseBody
	public JsonResult getChatRecord(Integer kefu_id,Integer user_id){ 
		KeFuChat chat = new KeFuChat();
		chat.setId(1);
		chat.setKefu_id(kefu_id);
		chat.setUser_id(user_id);
		List<KeFuChat> record = kefuService.findChatRecord(chat);
		return new JsonResult("",record);
	}
	
}
